package com.rpc.center.server.netty;

import com.rpc.center.event.eventtype.BaseEvent;
import com.rpc.center.event.eventtype.DiscoverEvent;
import com.rpc.center.event.eventtype.HeartBeatEvent;
import com.rpc.center.event.eventtype.PublishEvent;
import com.rpc.center.event.manager.EventManager;
import com.rpc.common.entity.request.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private EventManager eventManager;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //super.channelActive(ctx);
        System.out.println("有客户端连接");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //super.channelRead(ctx, msg);
        System.out.println("收到数据");

        BaseDTO basePacket=(BaseDTO) msg;
        PackageType type=basePacket.getPackageType();
        BaseEvent event=null;
        Channel channel=ctx.channel();
        if(type==PackageType.PUBLISH_PACKAGE){
            event=doPublish((PublishDTO)basePacket,channel);
        }else if(type==PackageType.DISCOVER_PACKAGE){
            event=doDiscover((DiscoverDTO)basePacket,channel);
        }else if(type==PackageType.HEARTBEAT_PACKAGE){
            event=doHeartBeat((HeartBeatDTO)basePacket,channel);
        }
        eventManager.dispatch(event);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
    }

    private PublishEvent doPublish(PublishDTO publishDTO, Channel channel){
        PublishEvent publishEvent=new PublishEvent();
        //publishEvent.setEventType(EventType.PUBLISH_EVENT);
        publishEvent.setChannel(channel);
        publishEvent.setMessage(publishDTO);
        return publishEvent;
    }

    private DiscoverEvent doDiscover(DiscoverDTO discoverDTO, Channel channel){
        DiscoverEvent event=new DiscoverEvent();
        //event.setEventType(EventType.DISCOVER_EVENT);
        event.setMessage(discoverDTO);
        event.setChannel(channel);
        return event;
    }

    private HeartBeatEvent doHeartBeat(HeartBeatDTO heartBeatDTO, Channel channel){
        HeartBeatEvent event=new HeartBeatEvent();
        event.setMessage(heartBeatDTO);
        event.setChannel(channel);
        return event;
    }
}
